<?php namespace App\Http\Services;

use App\ActiveParty;
use App\Activity;
use App\ActivityBrowseRecord;
use App\ActivityJoin;
use App\Admin;
use App\AiRecord;
use App\Classify;
use App\Comment;
use App\CommentLike;
use App\Coupons;
use App\DemandButt;
use App\Demands;
use App\ExpertLabel;
use App\ExpertQualificationImg;
use App\Experts;
use App\Files;
use App\Images;
use App\Merchant;
use App\MerchantAdmin;
use App\MerchantBanner;
use App\MerchantCustomer;
use App\MerchantLabel;
use App\Message;
use App\MessageRemind;

use App\User;
use App\UserCoupon;
use App\UserInfo;
use Carbon\Carbon;
use Auth;
use phpDocumentor\Reflection\Types\Self_;

class CommonManager
{

    /**
     * 获取用户的基本信息
     * @param $user_id
     * @return array|null
     */
    public static function getUserBasicInfo($user_id){
        if ($user_id==0 || $user_id=='' || $user_id==null)
            return [];

        $userInfo   = UserInfo::whereUserId($user_id)->first();

        $scoreTime = '';
        if($userInfo){
            $aiRecord = AiRecord::whereUserId($user_id)->orderBy("id","desc")->first();
            if($aiRecord){
                $userInfo->score = $aiRecord->score;
                $userInfo->save();

                $scoreTime = date("Y-m-d H:i:s",strtotime($aiRecord->created_at));
            }
        }

        $user       = User::whereId($user_id)->first();

        $result=[
            'user_id'     => '',
            'nickname'    => '',
            'realname'    => '',
            'sex'         => '',
            'photo_url'   => '',
            'province'    => '',
            'city'        => '',
            'area'        => '',
            'address'     => '',
            'birthday'     => '',
            'phone'       => '',
            'email'       => '',
            'integral'    => ''
        ];

        if ($userInfo) {
            $result['user_id']  = $userInfo->user_id;
            $result['nickname'] = $userInfo->nickname ?? '';
            $result['realname'] = $userInfo->realname ?? '';
            $result['sex']      = $userInfo->sex == 0 ? '保密' : ($userInfo->sex == 1 ? '男' : '女');
            $result['photo_url']= FileManager::getImgUrl($userInfo->photo_id);
            $result['province'] = $userInfo->province ?? '';
            $result['city']     = $userInfo->city ?? '';
            $result['area']     = $userInfo->area ?? '';
            $result['address']  = $userInfo->address ?? '';
            $result['birthday']  = $userInfo->birthday ?? '';
            $result['phone']    = $user->phone ?? '';
            $result['email']    = $user->email ?? '';
            $result['integral'] = $userInfo->integral ?? 0;
            $result['company_name'] = $userInfo->company_name ?? '';
            $result['score'] = $userInfo->score."%"  ?? 0;
            $result['score_time'] = $scoreTime;
        }
        return $result;
    }

    /**
     * 手机号格式验证
     * @param string $phone
     * @return bool
     */
    public static function phoneVerification($phone = ''){
        if(empty($phone))
            return false;

        if(!preg_match("/^(1[345678])[0-9]{9}$/", trim($phone)))
            return false;

        return true;
    }

    /**
     * 信用代码正则
     * @param string $uniformSocialCreditCode
     * @return bool
     */
    public static function uniformSocialCreditCodeVerification($uniformSocialCreditCode = ''){
        if(empty($uniformSocialCreditCode))
            return false;

        if(!preg_match("/[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}/", trim($uniformSocialCreditCode)))
            return false;

        return true;
    }

    /**
     * 身份证号格式验证
     * @param string $idCard
     * @return bool
     */
    public static function idCardVerification($idCard = ''){
        if(empty($idCard))
            return false;

        if(!preg_match("/^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/", trim($idCard)))
            return false;

        return true;
    }

    /**
     * 获取权限组名
     * @param string $groupName
     * @return string
     */
    public static function getGroupName($groupName = ''){
        if(empty($groupName))
            return '';

        switch ($groupName){
            case 'teacher' :
                return '导师管理';
                break;
            case 'course':
                return '课程管理';
                break;
            case 'order':
                return '订单管理';
                break;
            case 'staff':
                return '人员管理';
                break;
            case 'marketing':
                return '营销管理';
                break;
            case 'system':
                return '系统管理';
                break;
            default:
                return $groupName;
        }
    }

    public static function getPublishTime($the_time){
/*        //现在时间
        $now_time       = date("Y-m-d H:i:s",time());
        $now_year       = date('Y',time());
        $now_Hour       = date('H',time());
        //过去时间
        $pass_1_day     = self::getPassTime(1);
        $pass_7_day     = self::getPassTime(7);
        $hour=1;
        $pass_1_hour    = date('Y-m-d H:i:s',strtotime("$now_time - $hour  hour"));
        if (date_format($created_at,'Y') ==$now_year){
            //七天前
            if ($created_at < $pass_7_day){
                return date_format($created_at,'n-j');
            } else if ($created_at < $pass_1_day){
                //七天内，一天前
                $public_Time_Day=date_format($created_at,'d');
                return date('j天前',strtotime("$now_time - $public_Time_Day days"));
            } else {
                //一天内
                if ($created_at < $pass_1_hour){
                    //一小时前
                    $public_Time_Hour=date_format($created_at,'H');
                    return date('G小时前',strtotime("$now_time - $public_Time_Hour hours"));
                } else {
                    //一小时内
                    $public_Time_Min=date_format($created_at,'i');
                    $min=date('i',strtotime("$now_time - $public_Time_Min minutes"));
                    return intval($min).'分钟前';
                }
            }
        } else {
            return date_format($created_at,'Y-m-d');
        }*/

        $now_time = date("Y-m-d H:i:s", time());
        $now_year       = date('Y',time());
        //echo $now_time;
        $now_time = strtotime($now_time);
        $show_time = strtotime($the_time);
        $dur = $now_time - $show_time;
        if ($dur < 0) {
            return $the_time;
        } else {
            if ($dur < 60) {
                return $dur . '秒前';
            } else {
                if ($dur < 3600) {
                    return floor($dur / 60) . '分钟前';
                } else {
                    if ($dur < 86400) {
                        return floor($dur / 3600) . '小时前';
                    } else {
                        if ($dur < (24*60*60*7)) {//7天内
                            return floor($dur / 86400) . '天前';
                        } else  if (date_format($the_time,'Y') !=$now_year){
                            return $the_time;
                        } else {
                            return date_format($the_time,'n-j');
                        }
                    }
                }
            }
        }

    }
    public static function getPassTime($passDay=10){
        $todayTime = date("Y-m-d H:i:s",time());
//        $passDay=$passDay;
        //若干天之前的时间
        $lastTime   = date('Y-m-d H:i:s',strtotime("$todayTime - $passDay days"));
        return $lastTime;
    }

    /**
     * 查询用户所属商户
     * @param int $user_id
     * @return bool|int|mixed
     */
    public static function selectUserBelongMerchantToUserId($user_id = 0){
        if(empty($user_id))
            return false;

        $merchantAdmin = MerchantAdmin::whereUserId($user_id)->whereStatus(1)->first();
        if(!$merchantAdmin)
            return false;

        $merchant = Merchant::whereId($merchantAdmin->merchant_id)->whereStatus(1)->first();
        if(!$merchant)
            return false;

        return $merchant;
    }

    /**
     * 获取购物券
     * @param int $id
     * @param User|null $user
     * @return Coupons|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|\Illuminate\Support\Collection|mixed|object|null
     */
    public static function getCouponToId($id = 0,User $user = null){
        if(empty($id))
            return null;

        if(is_array($id)){
            /** @var Coupons $coupon */
            $couponList = Coupons::whereIn('id',$id)->get();
            if(count($couponList) > 0){
                foreach ($couponList as $coupon) {
                    if($user){
                        $userCoupon = UserCoupon::whereUserId($user->id)->whereCouponId($coupon->id)->first();
                        if($userCoupon){
                            $coupon->is_receive = 'yes';
                        }else{
                            $coupon->is_receive = 'no';
                        }
                    } else {
                        $coupon->is_receive = 'no';
                    }

                    if ($coupon->img_id)
                        $coupon->img_url=FileManager::getImgUrl($coupon->img_id);
                    else
                        $coupon->img_url=false;
                }
            }

            return $couponList;
        }else{
            if(!$user){
                $coupon=Coupons::whereId($id)->first();

                $coupon->img_url=FileManager::getImgUrl($coupon->img_id);

                if($coupon->type=="direct"){
                    $coupon->coupon_type="无门槛优惠券";
                }

                if($coupon->type=="satisfy"){
                    $coupon->coupon_type="满减优惠券";
                }
            }else{
                $coupon=Coupons::whereId($id)->first();
                if($coupon){
                    $userCoupon = UserCoupon::whereUserId($user->id)->whereCouponId($coupon->id)->first();

                    if($coupon->type=="direct"){
                        $coupon->coupon_type="无门槛优惠券";
                    }

                    if($coupon->type=="satisfy"){
                        $coupon->coupon_type="满减优惠券";
                    }

                    $coupon->img_url=FileManager::getImgUrl($coupon->img_id);


                    if($userCoupon){
                        $coupon->is_receive = 'yes';
                    }else{
                        $coupon->is_receive = 'no';
                    }
                }
            }

            return $coupon;
        }
    }

    /**
     * 获取商户
     * @param int $id
     * @return Merchant|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|\Illuminate\Support\Collection|mixed|object|null
     */
    public static function getMerchantToId($id = 0){
        if(empty($id))
            return null;

        if(is_array($id)){
            /** @var Merchant $merchant */
            $merchantList = Merchant::whereIn('id',$id)->get();
            if(count($merchantList) > 0){
                foreach ($merchantList as $merchant) {
                    $merchant->logo_img_url = FileManager::getImgUrl($merchant->logo_img_id);
                    $merchant->classify_name = '';

                    $classify = Classify::whereId($merchant->classify_id)->first();
                    if($classify){
                        $merchant->classify_name = $classify->name;
                    }

                    $merchantLabelArr = [];
                    $merchantLabelList = MerchantLabel::whereMerchantId($merchant->id)->orderBy('created_at','desc')->get();
                    if(count($merchantLabelList) > 0){
                        foreach ($merchantLabelList as $merchantLabel) {
                            array_push($merchantLabelArr,$merchantLabel->name);
                        }
                    }

                    $merchant->merchant_label_list = $merchantLabelArr;
                }
            }

            return $merchantList;
        }else{
            $merchant = Merchant::whereId($id)->first();
            if($merchant){
                $merchantBannerImgArr = [];
                $merchantBannerImgList = MerchantBanner::whereMerchantId($merchant->id)->orderBy('created_at','desc')->get();
                if(count($merchantBannerImgList) > 0){
                    foreach ($merchantBannerImgList as $merchantBannerImg) {
                        $merchantBannerImgUrl = FileManager::getImgUrl($merchantBannerImg->img_id);
                        array_push($merchantBannerImgArr,$merchantBannerImgUrl);
                    }
                }

                $merchant->merchant_banner_img_list = $merchantBannerImgArr;

                $merchant->classify_name = '';
                $classify = Classify::whereId($merchant->classify_id)->first();
                if($classify){
                    $merchant->classify_name = $classify->name;
                }

                $merchantLabelArr = [];
                $merchantLabelList = MerchantLabel::whereMerchantId($merchant->id)->orderBy('created_at','desc')->get();
                if(count($merchantLabelList) > 0){
                    foreach ($merchantLabelList as $merchantLabel) {
                        array_push($merchantLabelArr,$merchantLabel->name);
                    }
                }

                $merchant->merchant_label_list = $merchantLabelArr;
            }

            return $merchant;
        }
    }

    /**
     * 获取商户客户
     * @param int $id
     * @return MerchantCustomer|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|\Illuminate\Support\Collection|mixed|object|null
     */
    public static function getMerchantCustomerToId($id = 0){
        if(empty($id))
            return null;

        if(is_array($id)){
            /** @var MerchantCustomer $merchantCustomer */
            $merchantCustomerList = MerchantCustomer::whereIn('id',$id)->get();
            if(count($merchantCustomerList) > 0){
                foreach ($merchantCustomerList as $merchantCustomer) {
                    $merchantCustomer->user_info = null;
                    $userInfo = CommonManager::getUserBasicInfo($merchantCustomer->user_id);
                    if($userInfo){
                        $merchantCustomer->user_info = $userInfo;
                    }

                    $merchantCustomer->merchant_info = self::getMerchantToId($merchantCustomer->merchant_id);
                }
            }

            return $merchantCustomerList;
        }else{
            $merchantCustomer = MerchantCustomer::whereId($id)->first();
            if($merchantCustomer){
                $merchantCustomer->user_info = null;
                $userInfo = CommonManager::getUserBasicInfo($merchantCustomer->user_id);
                if($userInfo){
                    $merchantCustomer->user_info = $userInfo;
                }

                $merchantCustomer->merchant_info = self::getMerchantToId($merchantCustomer->merchant_id);
            }

            return $merchantCustomer;
        }
    }
}
